<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/4/4
 * Time: 下午2:37
 */

namespace Biz\module\Classes;

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderOperateLog as mOrderOperateLog;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\model\trade\OrderRefundQueue as mOrderRefundQueue;
use Biz\module\Classes\OrderRefund as clsOrderRefund;
use Biz\service\Event;
use Biz\service\trade\Pay as sPay;
use Biz\tools\Amount;


class OrderRefundQueue
{

    public function refundRmb($queueId, $isSys, $shopId, $uid, $orderNo, $refundOrderNo, $isConfirmReceipt, $refundRmb, $refundShippingAmount, $refundIntegralAmount, $refundCommissionAmount)
    {
        $nowTime = date('Y-m-d H:i:s');


        //所退的总钱数
        $totalRmb = Amount::format($refundRmb + $refundShippingAmount);


        //refundOrderInfo
        $refundInfo = mOrderRefund::get(['refund_order_no'], ['refund_order_no' => $refundOrderNo, 'status' => mOrderRefund::STATUS_REFUNDING]);
        if (empty($refundInfo)) {
            throw new \Exception('退款时，退款单状态不正确');
        }

        try {

            $result = mOrderRefund::action(function () use ($queueId, &$orderInfo, $orderNo, &$refundTransNo, $refundOrderNo, $nowTime, $totalRmb) {

                $orderInfo = mOrder::getOrderInfoFromMaster($orderNo);

                $refundTransNo = sPay::refundAmount($orderNo, $refundOrderNo, $orderInfo['pay_way'], $orderInfo['pay_no'], $totalRmb);

                if (empty($refundTransNo) && $orderInfo['pay_way'] != sPay::_PAY_WAYS_CUSTOMIZE_PAY_WAY) {
                    throw new \Exception('第三方退款失败，无返回数据');
                }

                //更新退款记录表
                $result = mOrderRefund::update([
                    'refund_way' => $orderInfo['pay_way'],
                    'refund_way_no' => $refundTransNo,
                    'confirm_time' => $nowTime,
                    'status' => mOrderRefund::STATUS_COMPLETE
                ], ['refund_order_no' => $refundOrderNo, 'status' => mOrderRefund::STATUS_REFUNDING]);

                if ($result->rowCount() == 0) {
                    throw new \Exception('退款时，第三方ID入库失败');
                }

                //更新退款对列表
                $result = mOrderRefundQueue::update([
                    'refund_rmb_way' => $orderInfo['pay_way'],
                    'refund_rmb_trans_no' => $refundTransNo,
                    'refund_rmb_time' => $nowTime,
                    'refund_rmb_status' => mOrderRefundQueue::REFUND_RMB_STATUS_COMPLETE
                ], ['id' => $queueId]);

                if ($result->rowCount() == 0) {
                    throw new \Exception('退款时，更新退款队列失败');
                }

                return true;
            });

            if ($result === false) {
                throw new \Exception(sprintf('出现错误，第三方退成功，但因数据库异常保存失败，queue_id=%s,refund_trans_no=%s', $queueId, $refundTransNo));
            }


            //后台成功退款到第三方支付
            Event::push(Event::ORDER_REFUND_REFUND_RMB_SUCCESS, [
                'queue_id' => $queueId,
                'order_no' => $orderNo,
                'refund_order_no' => $refundOrderNo,
                'refund_way' => $orderInfo['pay_way'],
                'refund_trans_no' => $refundTransNo,
                'confirm_time' => $nowTime,
                'uniq_idx' => ['refund_order_no', 'event_tag']
            ]);

            //查询退款详情
            $orderInfo = mOrder::getOrderInfo($orderNo);

            //部分发货时要修复订单状态
            clsOrderRefund::updateOrderStatusByPartShip($orderNo, $orderInfo['status']);


        } catch (\Exception $e) {

            $addTime = date('Y-m-d H:i:s');

            $textContent = '确认退款并打款失败。' . $e->getMessage();


            $logInfo = mOrderOperateLog::getLogList(['ORDER' => ['id' => ['DESC']], 'trade_type' => mOrderOperateLog::TRADE_TYPE_ORDER_REFUND, 'shop_id' => $shopId, 'order_no' => $orderNo, 'refund_order_no' => $refundOrderNo]);
            $addLog = true;
            foreach ($logInfo as $row) {
                if ($row['text_content'] == $textContent) {
                    $addLog = false;
                }
            }
            if ($addLog) {
                //增加操作日志
                mOrderOperateLog::createLog($shopId, $orderNo, mOrderOperateLog::TRADE_TYPE_ORDER_REFUND, $opLog = [
                    'operate_type' => mOrderOperateLog::OPERATE_TYPE_REFUND_RMB_ERROR,
                    'operate_user_type' => mOrderOperateLog::OPERATE_USERTYPE_SYS,
                    'operate_uid' => 0,
                ], $refundOrderNo, $textContent, '', [], $addTime);
            }

            throw $e;
        }

    }


}